<template>
  <div>
    <div class="flex">
      <!-- <el-button type="primary" v-if="is_admin_view == 0" @click="CreatCancle = true">添加专利</el-button> -->
      <el-button size="mini" type="primary" v-if="is_admin_view == 0" @click="uploadDialog = true">导入专利</el-button>

      <p style="font-size:14px;margin-left: 20px;">更新周期：{{ data.start_time }} 至 {{ data.end_time }}</p>
    </div>
    <CreatTable @NotGlAdd="NotGlAdd" @adminGlAdd="adminGlAdd" @getListArr="getListArr" :ListArr="ListArr"
      :handelType="handelType" :title="name" />
    <!--        <el-pagination
        background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.page"
          :page-size="page.page_size"
          layout="total, prev, pager, next, jumper"
          :total="page.count"
          align='left'
        ></el-pagination> -->
    <Service />

    <!-- 新增专利 -->
    <el-dialog :destroy-on-close="true" @close="Canle('form')" :close-on-click-modal='false' title="添加专利"
      :visible.sync="CreatCancle" width="40%" center>
      <el-form ref="form" :model="form" label-width="100px" label-position="left">
        <el-form-item prop="name" :error="form[index].message" :label="'专利申请号' + (index + 1)"
          v-for="(item, index) in FormArr" :key="item">
          <el-input type="name" @input="changeInput(index)" style="width:80%;" placeholder="请输入专利申请号"
            v-model="form[index].name"></el-input>
          <el-button type="primary" v-if="(FormArr - 1) == index" @click="addItem(index)">继续添加</el-button>
          <el-button type="danger" v-else @click="deleteItem(index)">删除</el-button>
          <!-- primary danger-->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="button" class="pubBtn2" @click="Canle('form')">取消操作</el-button>
        <el-button type="button" class="pubBtn" @click="CreatSave('form')">确定添加</el-button>
      </span>
    </el-dialog>

    <!-- 新增申请中专利 -->
    <el-dialog title="新增申请中专利" :visible.sync="NotAddDialog" width="40%" center>
      <el-form ref="form" :model="NotAdd" label-width="100px" label-position="left">
        <el-form-item label="专利申请号">
          <el-input v-model="NotAdd.sno"></el-input>
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="NotAdd.apc"></el-input>
        </el-form-item>
        <el-form-item label="发明人">
          <el-input v-model="NotAdd.aspo"></el-input>
        </el-form-item>
        <el-form-item label="专利名称">
          <el-input v-model="NotAdd.tic"></el-input>
        </el-form-item>
        <el-form-item label="专利申请时间">
          <el-date-picker class="NotPicker" v-model="NotAdd.ad" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专利类型">
          <el-select class="NotSelect" v-model="NotAdd.type" placeholder="请选择" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div style="display: flex;justify-content: flex-end;">
            <!-- <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="NotAddDialog = false">取消</el-button> -->
            <el-button type="button" class="pubBtn2" @click="NotAddDialog = false">取消操作</el-button>
            <el-button type="button" class="pubBtn" @click="onSubmit">确定添加</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 导入专利 -->
    <el-dialog title="导入专利" :visible.sync="uploadDialog" width="23%">
      <!-- <el-upload :show-file-list="false" class="upload-demo" :action="action" :data="{'user_id':user_id}"
        :on-success="handleSuccess" :on-error="handleError" :before-remove="beforeRemove" :limit="1"
        :on-exceed="handleExceed" :file-list="fileList">
        <el-button size="small" type="primary">点击导入</el-button>
      </el-upload> -->

      <div style="padding: 0 20px;">
        <el-upload class="upload-demo" drag :action="action" multiple :data="{'user_id':user_id}" ref="upload"
          :on-success="handleSuccess" :on-error="handleError" :before-remove="beforeRemove" :limit="1"
          :on-exceed="handleExceed" :file-list="fileList" :auto-upload="false">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>

        <div class="TemplateText err" v-if="is_true == 0"><i class="el-icon-warning"></i>您上传的文件有误，请<span
            @click="errupload">下载</span>查看修改后重新上传</div>

        <div class="TemplateText">1、请先<span @click="download">下载</span>模版文件</div>
        <div class="TemplateText">2、按照文件模版格式添加专利数据后上传</div>

        <div style="display: flex;justify-content: flex-end;">
          <el-button type="primary" @click="upload">立即上传</el-button>
          <el-button @click="uploadDialog = false">取消</el-button>
        </div>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  mapGetters
} from 'vuex'
import {
  patentIndexNew,
  applyAdd,
  agentimport,
  import_export
} from "@/api"
import {
  insert,
  patentExport
} from "@/api/user"
import {
  VUE_APP_BASE_API
} from "@/config.js"
import CreatTable from "@/components/CreatTable/CreatTable"
import Service from '@/components/Service'
import { log } from 'util'
export default {
  data() {
    return {
      fileList: [],
      addVal: "",
      action: `${VUE_APP_BASE_API}/v1/import/agentimport`,
      NotAddDialog: false,
      uploadDialog: false,
      user_id: this.$store.state.user.id,
      NotAdd: {
        sno: "",
        ad: "",
        apc: "",
        aspo: "",
        tic: "",
        type: '',
      },
      options: [{
        value: 1,
        label: '发明专利'
      },
      {
        value: 2,
        label: '实用新型'
      },
      {
        value: 3,
        label: '外观设计'
      }
      ],
      is_true: 1,
      import_id: null,
      dialogVisible: false,
      ListArr: [],
      page: [],
      tisp: false,
      handelType: 2,
      data: [],
      // name: '公司名称',
      CreatCancle: false,
      form: [{
        name: '',
        message: ""
      }],
      FormArr: 1
    }
  },
  components: {
    CreatTable,
    Service
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'roles',
      'type',
      'is_admin_view'
    ]),
  },
  mounted() {
    this.getList();
    // console.log(this.is_admin_view,'is_admin_view');
  },
  methods: {
    uploadFile(file) {
      // console.log(file);
      this.fileList = []
      agentimport({
        file: file.action,
        user_id: this.$store.state.user.id
      }).then(res => {
        // console.log(res);
        // if (res.code == 200) {
        //   this.$message({
        //     message: '导入成功',
        //     type: 'success'
        //   });
        //   this.getList();
        // } else {
        //   this.$message({
        //     message: res.msg,
        //     type: 'error'
        //   });
        // }
      })
    },
    onSubmit() {
      applyAdd({
        user_id: this.$store.state.user.id,
        sno: this.NotAdd.sno,
        ad: this.NotAdd.ad,
        apc: this.NotAdd.apc,
        aspo: this.NotAdd.aspo,
        tic: this.NotAdd.tic,
        type: this.NotAdd.type,
      }).then(res => {
        this.ListArr = []
        this.getList();
        this.NotAddDialog = false;
        this.NotAdd = {
          sno: "",
          ad: "",
          apc: "",
          aspo: "",
          tic: "",
          type: '',
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      if (response.data.is_true) {
        this.$notify({
          title: '成功',
          message: '上传成功',
          type: 'success'
        });
        this.ListArr = []
        this.getList();
        this.uploadDialog = false;
      }
      this.fileList = [];
      this.is_true = response.data.is_true
      this.import_id = response.data.import_id
    },
    async errupload() {
      // const res = await import_export({
      //   import_id: this.import_id
      // })

      const res = await patentExport({
        liusongjing: 2,
        import_id: this.import_id
      });
      // console.log(res, 'res错误的文件');

      const blob = new Blob([res.data]);
      const fileName = `${this.name}专利统计.xls`;
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
      this.$message.success("导出成功");
    },
    handleError(err, file) {
      // console.log(err, file);
      this.$notify.error({
        title: '错误',
        message: '上传失败'
      });
    },
    adminGlAdd() {
      this.CreatCancle = true
    },
    NotGlAdd() {
      // console.log('NotGlAdd');
      this.NotAddDialog = true
    },
    getListArr() {
      this.ListArr = []
      this.getList();
    },
    upload() {
      this.$refs.upload.submit();
    },
    async getList() {
      try {
        const res = await patentIndexNew({
          type: 0
        });
        // console.log('res.list_all', res.list_all)
        let data
        if (res.list_all) {
          data = res.list_all.children.filter(item => item.id == 999999999999998)
          res.list_all.children = res.list_all.children.filter(item => item.id != 999999999999998)
        }
        this.ListArr.push(res.list_all);
        this.ListArr.push(data[0]);
        this.page = res.page
        this.data = res
      } catch (e) {
        this.$message.error(e.message);
      }

    },
    rowClick(row) {

    },
    changeInput(index) {
      this.form[index].message = ''
    },
    deleteItem(index) {
      this.FormArr--;
      this.form.splice(index, 1)
    },
    addItem(index) {
      if (this.form[index].name == '') {
        this.$message.error("请填写专利申请号")
      } else {
        this.FormArr++;
        this.form.push({
          name: '',
          message: ""
        })
      }
    },
    Canle(formName) {
      this.CreatCancle = false;
      this.$refs[formName].resetFields();
      this.form = [{
        name: '',
        message: ""
      },
      ]
      this.FormArr = 1
    },
    async CreatSave(formName) {
      // const arr = this.form.map(item=>item.name)
      try {
        let time
        const res = await insert({
          ano: this.form,
          ptype: 0
        });
        // console.log(res == "");
        if (res == "") {
          this.$message.success("添加成功")
          this.$refs[formName].resetFields();
          this.form = [{
            name: '',
            message: ""
          },
          ]
          this.FormArr = 1
          // this.getList();
          this.CreatCancle = false;
          time = setTimeout(async () => {
            const res = await patentIndexNew({
              type: 0
            });
            this.ListArr = []
            this.ListArr.push(res.list_all);
            this.page = res.page
            this.data = res
            clearTimeout(time);
          }, 1000)
        } else {
          res.data.data.map((item, index) => {
            this.form.map((i, n) => {
              if (index == n && item != true) {
                this.form[n].message = item;
              }
            })
          })
        }
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // //每页下拉显示数据
    // async handleSizeChange(size) {
    //   try{
    //     const res =await rivalsList({
    //        page:size,
    //     })
    //     this.ListArr = res.list;
    //     this.page = res.page
    //   } catch (e){
    //     this.$message.error(e.message)
    //   }

    // },
    // //点击第几页
    // async handleCurrentChange(currentPage) {
    //   try{
    //     const res =await rivalsList({
    //        page:currentPage,
    //     })
    //     this.ListArr = res.list;
    //     this.page = res.page
    //   } catch (e){
    //     this.$message.error(e.message)
    //   }
    // },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    download() {
      //下载文件并自定义文件名
      const fileName = `${this.name}专利统计模版.xls`;
      // const blob = new Blob(['http://sdipsc.oss-cn-shanghai.aliyuncs.com/b583aed08734176e021d944f939b26c4'], {
      //   type: "application/vnd.ms-excel"
      // });
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = 'http://sdipsc.oss-cn-shanghai.aliyuncs.com/84833d082f35026c49d036b998f41b1a.xls';
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);

      // window.open('http://sdipsc.oss-cn-shanghai.aliyuncs.com/84833d082f35026c49d036b998f41b1a.xls')
    
    }

  }
}
</script>

<style scoped lang="less">
.diff {
  color: #F05C6C;
}

.NotPicker {
  width: 100%;
}

.NotSelect {
  width: 100%;
}

.TemplateText {
  margin-top: 20px;
  margin-bottom: 30px;
  font-size: 14px;

  // font-weight: bold;
  span {
    color: #409EFF;
    cursor: pointer;
  }
}

::v-deep .el-upload {
  width: 100%;

  .el-upload-dragger {
    width: inherit !important;
    ;
  }
}

.err {
  color: #F05C6C;
}
</style>
